package com.kcht.np.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kcht.np.common.jwt.JwtUser;
import com.kcht.np.constant.Constants;
import com.kcht.np.constant.UserConstants;
import com.kcht.np.core.domain.entity.SysMenu;
import com.kcht.np.entity.SysPermission;
import com.kcht.np.service.ISysMenuService;
import com.kcht.np.service.SysPermissionService;
import com.kcht.np.util.JsonResult;
import com.kcht.np.vo.page.QueryParameter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
  * <p>
  * 权限管理 控制器
  * </p>
  *
  * @Package:        com.kcht.np.mp.controller
  * @Description:    权限管理 控制器
  * @Author:         liuqi
  * @CreateDate:     2020/3/31 11:27
 */

@Slf4j
@Api(tags = "[ 权限管理 ] 权限管理")
@RestController
@RequestMapping("/sys/permission")
public class SysPermissionController{

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysMenuService menuService;

    /*-------------------查询--------------------------*/
    @ApiOperation(value = "查询所有", notes = "查询所有")
    @GetMapping("/all")
    @PreAuthorize("hasAnyAuthority('pre_perm')")
    public JsonResult queryPermissions() {

        return JsonResult.success(permissionService.list());
    }

    @ApiOperation(value = "分页", notes = "分页 查询所有")
    @GetMapping("/page")
    @PreAuthorize("hasAnyAuthority('pre_perm')")
    public JsonResult findAll(QueryParameter parameter) {
        IPage<SysPermission> page = new Page<>(parameter.getPageNum(), parameter.getPageSize());
        IPage<SysPermission> iPage = permissionService.page(page);
        return JsonResult.success(iPage.getPages(),iPage.getTotal(), iPage.getRecords());
    }


    /**
     * kchtnp2.0.0:菜单管理获取菜单列表
     */
    @ApiOperation(value = "获取菜单列表",notes ="菜单管理:查询菜单1" )
    @PreAuthorize("hasAnyAuthority('pre_perm')")
    @GetMapping("/list")
    public JsonResult getMenulist(SysMenu menu)
    {
        JwtUser jwtUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<SysMenu> menus = menuService.selectMenuList(menu, jwtUser.getUid());
        return JsonResult.success(menus);
    }


    /**
     * 根据菜单编号获取详细信息
     */
    @ApiOperation(value = "根据菜单编号获取详细信息",notes ="菜单管理:修改菜单1" )
    @PreAuthorize("hasAnyAuthority('pre_perm')")
    @GetMapping(value = "/{menuId}")
    public JsonResult getInfo(@PathVariable Long menuId)
    {
        return JsonResult.success(menuService.selectMenuById(menuId));
    }


    /*--------------------创建---------------*/
    /**
     * kchtnp2.0.0:菜单管理新增菜单
     */
    @ApiOperation(value = "新增菜单",notes ="菜单管理:增加" )
    @PreAuthorize("hasAnyAuthority('pre_perm:create')")
    @PostMapping
    public JsonResult add(@Validated @RequestBody SysMenu menu)
    {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu)))
        {
            return JsonResult.fail("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(menuService.checkResourcesUnique(menu)))
        {
            return JsonResult.fail("新增菜单'" + menu.getMenuName() + "'失败，权限标识已经存在");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS))
        {
            return JsonResult.fail("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        int i = menuService.insertMenu(menu);
        return JsonResult.success(i);
    }


    /**
     * 修改菜单
     */
    @ApiOperation(value = "修改菜单",notes ="菜单管理:修改菜单" )
    @PreAuthorize("hasAnyAuthority('pre_perm:update')")
    @PutMapping
    public JsonResult edit(@Validated @RequestBody SysMenu menu)
    {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu)))
        {
            return JsonResult.fail("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(menuService.checkResourcesUnique(menu)))
        {
            return JsonResult.fail("修改菜单'" + menu.getMenuName() + "'失败，权限标识已经存在");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS))
        {
            return JsonResult.fail("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        else if (menu.getMenuId().equals(menu.getParentId()))
        {
            return JsonResult.fail("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }

        int i = menuService.updateMenu(menu);
        System.out.println(i);
        return JsonResult.success(i);
    }



    /**
     * 删除菜单
     */
    @ApiOperation(value = "删除菜单",notes ="菜单管理:删除菜单" )
    @PreAuthorize("hasAnyAuthority('pre_perm:delete')")
    @DeleteMapping("/{menuId}")
    public JsonResult remove(@PathVariable("menuId") Long menuId)
    {
        if (menuService.hasChildByMenuId(menuId))
        {
            return JsonResult.fail("存在子菜单,不允许删除");
        }
        if (menuService.checkMenuExistRole(menuId))
        {
            return JsonResult.fail("存在角色被分配该菜单,不允许删除");
        }
        int i = menuService.deleteMenuById(menuId);
        System.out.println(i);
        return JsonResult.success(i);
    }
}
